const getFuncOnLoopCondition = async (executor, condition, delay = 10, timeout = 5 * 60 * 1000) => {
  if (typeof executor !== 'function') throw new Error(`getFuncOnLoopCondition: executor must be a function, but got ${typeof executor}`)
  if (typeof condition !== 'function') throw new Error(`getFuncOnLoopCondition: condition must be a function, but got ${typeof condition}`)

  const start = performance.now()
  let timer = null

  return new Promise((resolve, reject) => {
    const loop = async function () {
      if (performance.now() - start > timeout) {
        // 超时了
        if (timer) clearTimeout(timer)
        return reject(`调用超时了`)
      }

      try {
        const result = await executor() // 执行异步请求函数
        const finished = await condition(result) // 检查条件是否满足
        if (finished) {
          if (timer) {
            clearTimeout(timer)
            timer = null
          }
          resolve(executor) // 此时已经满足条件，直接返回函数，函数主体为执行函数
        } else {
          timer = setTimeout(loop, delay) // 不断轮询
        }
      } catch (error) {
        reject(error)
        clearTimeout(timer)
        timer = null
      }
    }
    loop()
  })
}

export default getFuncOnLoopCondition
